//
//  SQLiteManager.swift
//  hondaPOC
//
//  Created by Chao.W on 2020/2/20.
//  Copyright © 2020 Army_Ma. All rights reserved.
//

import UIKit
//import FMDB
import zlib

class SQLiteManager: NSObject {

    private static let manager : SQLiteManager = SQLiteManager()
    class func shareManager() -> SQLiteManager {
        return manager
    }
    
    var db = FMDatabase()
    
    func openDB() -> () {
        let path = getDataBasePath()
        db = FMDatabase(path: path)
        
        if !db.open() {
            print("打开数据库失败")
            return
        }
        
        createTable()
    }
       
    func createTable() {
    
        let sql = "CREATE TABLE IF NOT EXISTS Analytics_data ( \n" +
        "'id' INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
        "'data_type' TEXT, \n" +
        "'data_time' DATE, \n" +
        "'data' TEXT )"
        
        if db.executeUpdate(sql, withArgumentsIn: []) {
            print("创建表成功")
        }
        else{
            print("创建表失败")
        }
        
    }
    
    func getDataBasePath() -> String{
        let docuPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let dbPath = docuPath.appending("/AnalyticsData.db")
        print(dbPath)
        return dbPath
    }
    
    var dataJson = [String:Any]()
    
    func insertData(dataType:String, analyticsData:Any) -> () {

        if dataType == "AppStart" {
            let data : AnalyticsDataStart = analyticsData as! AnalyticsDataStart
            dataJson = data.toJSON()!
        }
        else if dataType == "AppEnd" {
            let data : AnalyticsDataEnd = analyticsData as! AnalyticsDataEnd
            dataJson = data.toJSON()!
        }
        else if dataType == "AppViewScreen" {
            let data : AnalyticsDataView = analyticsData as! AnalyticsDataView
            dataJson = data.toJSON()!
        }
        else if dataType == "AppClick" {
            let data : AnalyticsDataClick = analyticsData as! AnalyticsDataClick
            dataJson = data.toJSON()!
        }
        let dbQueue : FMDatabaseQueue = FMDatabaseQueue(path:getDataBasePath())!
        
        dbQueue.inTransaction { (db, rollback) in
            let sql = "INSERT INTO Analytics_data (data_type, data_time, data) VALUES (?, ?, ?)"
            let time = Date().timeIntervalSince1970*1000
            let dataTime = String(format: "%0.f", time)
            
            let data : NSData! = try? JSONSerialization.data(withJSONObject: dataJson, options: []) as NSData?
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
            
            let result = db.executeUpdate(sql, withArgumentsIn: [dataType, dataTime, JSONString ?? ""])
            
            if result {
                print("DB Insert Success.")
            } else {
                print("DB Insert Fail.")
            }
        }
        
        DataManager.dataShouldUpload() //数据上传
        
    }
    
    var lastId = 0
    
    func sqlData() -> NSInteger {
        var dataCount = 0

        let dbQueue : FMDatabaseQueue = FMDatabaseQueue(path:getDataBasePath())!
        dbQueue.inTransaction { (db, rollback) in
            var idArr = [Int]()
            
            /**SQL DB*/
            let sqlSelect = "SELECT * FROM Analytics_data"
            let resultSet = db.executeQuery(sqlSelect, withArgumentsIn: [])
            guard resultSet != nil else {return}
            while(resultSet!.next()) {
                let id : String = (resultSet?.string(forColumn: "id"))!
                idArr.append(Int(id)!)
                dataCount += 1
            }
            if !idArr.isEmpty {
                lastId = idArr.last!
            }
        }
        return dataCount
    }
    
    func deleteData() {
        /**Delete DB*/
        let dbQueue : FMDatabaseQueue = FMDatabaseQueue(path:getDataBasePath())!
        dbQueue.inTransaction { (db, rollback) in
            let deleteSql = "DELETE FROM Analytics_data WHERE id <= ?"
            let deleteResult = db.executeUpdate(deleteSql, withArgumentsIn: [lastId])
            if deleteResult {
                print("DB Delete Success.")
            }
        }
    }
    
}

class DataManager {
    static var appID = ""
    
    class func dataShouldUpload() -> () {

        let dataCount = SQLiteManager.shareManager().sqlData()
        if dataCount >= 200 {
            /**数据上传*/
            uploadData()
        }
    }
    
    class func uploadData() {
        
        let path = SQLiteManager.shareManager().getDataBasePath()
        let dbData : Data = FileManager.default.contents(atPath: path)!
        
        let postUrl = "https://cloud.carautocloud.com/rcg/m85/analysis/behavior/upload"
        let uuid = UIDevice.current.identifierForVendor!.uuidString
//        let appId = "c3cf2837665d010ba44e0d105b031cca"
        
        var headers:HTTPHeaders = [:]
        headers["appID"] = DataManager.appID
        
        AF.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(dbData, withName: "db", fileName: "data.db", mimeType: "application/octet-stream")
            multipartFormData.append(Data(uuid.utf8), withName: "uuid")
            multipartFormData.append(Data(DataManager.appID.utf8), withName: "app_id")
            
        }, to: postUrl, usingThreshold: MultipartFormData.encodingMemoryThreshold, method: .post, headers: headers, interceptor: nil, fileManager: .default).responseJSON { (response) in
            
            let resultDic : [String : Any] = response.result.success as! [String : Any]
            let statusCode : NSInteger = resultDic["statusCode"] as! NSInteger
            if statusCode == 200 {
                SQLiteManager.shareManager().deleteData()
            }
            
            debugPrint(response)
        }
    }
    
}

